import 'dart:convert';
import 'dart:io';

import 'package:crypto/crypto.dart';
import 'package:lib_common/lib_common.dart';
import 'package:lib_http/lib_http.dart';
import 'package:package_info_plus/package_info_plus.dart';

class HttpInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
    var headers = options.headers;

    // platform
    headers["platform"] = Platform.operatingSystem;

    var mills = DateTime.timestamp().millisecondsSinceEpoch;
    // timestamp
    options.headers["timestamp"] = "$mills";

    // token
    var token = SpUtil.getString(CacheConstants.userToken) ?? "";
    if (token.isNotEmpty) {
      headers["token"] = token;

      if (options.method == HttpManager.getMethod) {
        options.queryParameters["c"] = md5.convert(const Utf8Encoder().convert(token));

        if (options.queryParameters["is_refresh"] == true) {
          options.queryParameters["timestamp"] = "$mills";
        }
      }
    }

    // channel
    var runtimeChannel = await AppManager.getInstance().getRuntimeChannel();
    headers["channel"] = runtimeChannel;

    // version
    var version = await _getVersion();
    options.headers["version"] = version;

    super.onRequest(options, handler);
  }

  /// 获取应用版本
  Future<String> _getVersion() async {
    var packageInfo = await PackageInfo.fromPlatform();
    var version = packageInfo.version;
    var buildNumber = packageInfo.buildNumber;
    return "$version-$buildNumber";
  }
}
